<script setup lang="ts">
import { useUserStore } from "../store/user.ts";
import DefaultLayout from "../layouts/DefaultLayout.vue";
import * as AddressApi from '../apis/address.ts'
import * as HistoryApi from "../apis/history.ts";
import { reactive, ref, watch } from "vue";
import { Address } from "../apis/address.ts";
import EditIcon from "../icons/EditIcon.vue";
import { pcaTextArr } from "element-china-area-data";
import { ElMessage } from "element-plus";
import DeleteIcon from "../icons/DeleteIcon.vue";
import router from "../router";

const userStore = useUserStore()
const addressList = ref<Address[]>([]);
const dialogVisible = ref(false)
let addressForm = reactive({}) as Address;
const selectedAddress = ref<string[]>([]);
const historyOrders = ref([])
const updateModel = ref(false)
const loading = ref(true)
const orderDetail = reactive({ data: {}, visible: false })
const getAddressList = () => {
  console.log('用户id：' + userStore.id)
  AddressApi.getAddressList(userStore.id)
    .then((res) => {
      addressList.value = res.data
    })
}
const handleOpenDialog = () => {
  dialogVisible.value = true
}

watch(userStore, () => {
  getAddressList();
  getHistoryOrders();
})

const getHistoryOrders = () => {
  HistoryApi.getHistoryList(userStore.id)
    .then((res) => {
      historyOrders.value = res.data.sort((a, b) => a.oState < b.oState ? -1 : 1)
      loading.value = false
    })
}

if (userStore.isLogin) {
  getAddressList();
  getHistoryOrders();
}

const checkForm = () => {
  if (addressForm.aConsignee == null || addressForm.aConsignee == '') {
    ElMessage({
      message: '收货人不能为空',
      type: 'warning'
    })
    return false;
  }
  if (addressForm.aPhone == null || addressForm.aPhone == '') {
    ElMessage({
      message: '收货电话不能为空',
      type: 'warning'
    })
    return false;
  }
  if (addressForm.aPhone != null && addressForm.aPhone != '') {
    if (!/^1[3456789]\d{9}$/.test(addressForm.aPhone)) {
      ElMessage({
        message: '手机号格式不正确',
        type: 'warning'
      })
      return false;
    }
  }
  if (addressForm.aEmail == null || addressForm.aEmail == '') {
    ElMessage({
      message: '邮箱不能为空',
      type: 'warning'
    })
    return false;
  }
  if (addressForm.aEmail != null && addressForm.aEmail != '') {
    if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(addressForm.aEmail)) {
      ElMessage({
        message: '邮箱格式不正确',
        type: 'warning'
      })
      return false;
    }
  }
  if (addressForm.aSex == null || addressForm.aSex == '') {
    ElMessage({
      message: '性别不能为空',
      type: 'warning'
    })
    return false;
  }

  if (!selectedAddress.value || selectedAddress.value.size == 0) {
    ElMessage({
      message: '地址不能为空',
      type: 'warning'
    })
    return false;
  }
  if (addressForm.aDetail == null || addressForm.aDetail == '') {
    ElMessage({
      message: '详细地址不能为空',
      type: 'warning'
    })
    return false;
  }

  return true;
}
const handleConfirm = () => {
  if (!checkForm()) return;

  addressForm.aProvinceName = selectedAddress.value[0]
  addressForm.aCityName = selectedAddress.value[1]
  addressForm.aDistrictName = selectedAddress.value[2]
  addressForm.userId = userStore.id

  if (updateModel.value) {
    handleUpdateAddress();
  } else {
    handleAddAddress();
  }
}
const clickUpdate = (address: Address) => {
  addressForm = reactive({ ...address });
  handleOpenDialog();
  selectedAddress.value = [
    address.aProvinceName,
    address.aCityName,
    address.aDistrictName
  ]
  updateModel.value = true;

}
const handleUpdateAddress = () => {
  AddressApi.updateAddress(addressForm)
    .then((res) => {
      if (res.code === 200) {
        ElMessage({
          message: '修改成功',
          type: 'success'
        })
        cleanForm();
        getAddressList();
      } else {
        ElMessage({
          message: res.message,
          type: 'warning'
        })
      }

    })
    .catch((res) => {
      console.log(res)
    })
}
const handleAddAddress = () => {
  AddressApi.addAddress(addressForm)
    .then((res) => {
      if (res.code === 200) {
        ElMessage({
          message: '添加成功',
          type: 'success'
        })
        cleanForm();
        getAddressList();
      } else {
        ElMessage({
          message: res.message,
          type: 'warning'
        })
      }

    })
    .catch((res) => {
      console.log(res)
    })
}
const cleanForm = () => {
  console.log("clean ..... ")
  addressForm = reactive({}) as Address;
  selectedAddress.value = []
  dialogVisible.value = false
  updateModel.value = false
}
const handleDelete = (aId: string) => {
  AddressApi.deleteAddress(aId)
    .then((res) => {
      if (res.code === 200) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
        getAddressList();
      } else {
        ElMessage({
          message: res.message,
          type: 'warning'
        })
      }
    })
}

const formatDateTime = (time: string) => {
  const year = time.substring(0, 4)
  const month = time.substring(5, 7)
  const day = time.substring(8, 10)
  const hours = time.substring(11, 13)
  const minutes = time.substring(14, 16)
  const seconds = time.substring(17, 19)
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}
const formatAddress = (aId) => {
  let address = addressList.value.find(item => item.aId == aId);
  return address.aProvinceName + address.aCityName + address.aDistrictName;
}
const handelViewOrderDetail = (data) => {
  orderDetail.data = data
  orderDetail.visible = true
}

const clickCart = () => {
  router.push({ name: 'ShoppingCart' })
}

</script>

<template>
  <DefaultLayout>
    <el-dialog v-model="dialogVisible" width="600" title="地址信息" :before-close="cleanForm" :show-close="false">
      <div class="grid grid-cols-2 gap-3">
        <el-input size="large" v-model="addressForm.aConsignee" placeholder="收货人" />
        <el-input size="large" v-model="addressForm.aPhone" placeholder="收货电话" />
        <el-input size="large" v-model="addressForm.aEmail" placeholder="邮箱" />
        <el-select popper-class="mySelect" size="large" placeholder="性别" v-model="addressForm.aSex">
          <el-option value="男" label="男" />
          <el-option value="女" label="女" />
        </el-select>
        <el-cascader size="large" :options="pcaTextArr" v-model="selectedAddress" placeholder="省市区">
        </el-cascader>
        <el-input size="large" v-model="addressForm.aDetail" placeholder="详细地址" />
      </div>
      <template #footer>
        <button
          class="bg-[#fdf5f6] border border-red-500 text-red-500 px-4 py-2 rounded-lg hover:bg-opacity-70 transition duration-300 ease-in-out"
          @click="cleanForm">取消</button>
        <button
          class="bg-primary ml-4 px-4 py-2 text-white rounded-lg hover:bg-opacity-70 transition duration-300 ease-in-out"
          @click="handleConfirm">确定</button>
      </template>
    </el-dialog>


    <div class="flex mx-40 mt-6">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }" @click="updatePage('/')">首页</el-breadcrumb-item>
        <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      </el-breadcrumb>
    </div>


    <div class="flex mx-40 my-6 space-x-10 items-start">
      <div class="bg-white p-3 shadow-lg rounded-lg w-2/6">
        <div class="flex space-x-5 justify-around">
          <img src="../assets/image/avatar.png" alt="avatar" class="w-24 h-24 rounded-full" />
          <div class="w-32 text-center">
            <span class="text-2xl font-bold mt-1">{{ userStore.username }}</span>
            <div class="text-sm text-slate-500 mt-5">我的账号</div>
            <span class="text-sm text-slate-500">{{ userStore.id }}</span>
          </div>
        </div>
        <div class="flex cursor-pointer border-b border-slate-300 pb-4 space-x-5 text-center mt-5 justify-around">
          <div @click="router.push({ name: 'Dashboard' })"
            class="hover:text-primary border-r border-slate-300 w-1/2 transition duration-300 ease-in-out">
            商城首页
          </div>
          <div class="hover:text-primary w-1/2 transition duration-300 ease-in-out" @click="clickCart">我的购物车</div>
        </div>
        <div class="relative mt-2">
          <h2 class="text-xl my-3 font-bold">收货地址</h2>
          <button @click="handleOpenDialog"
            class="absolute right-1 top-0 bg-primary hover:bg-opacity-70 text-white p-1 px-2 rounded-lg transition duration-300 ease-in-out">
            添加
          </button>
          <div class="h-64 overflow-y-auto">
            <div class="flex items-center justify-center h-full" v-if="addressList.length === 0">
              <div class="text-center text-slate-500">
                <img src="../assets/image/empty.png" alt="empty" class="mx-auto" />
                <div class="mt-5">暂无收货地址</div>
              </div>
            </div>
            <div class="relative bg-slate-100 rounded-lg cursor-pointer p-2 mb-3 h-20" v-for="address in addressList">
              <h3 class="absolute top-2 text-sm text-slate-800 font-bold">收货人：{{ address.aConsignee }}</h3>
              <h3 class="absolute right-1 top-2.5 text-xs text-slate-800 font-bold">手机号：{{ address.aPhone }}</h3>
              <h3 class="absolute bottom-2 text-xs max-w-sm truncate text-slate-600">
                地址：
                {{ address.aProvinceName }}
                {{ address.aCityName }}
                {{ address.aDistrictName }}
                {{ address.aDetail }}
              </h3>
              <el-popconfirm title="是否删除该地址？" width="200" confirm-button-text="确定" cancel-button-text="取消"
                @confirm="handleDelete(address.aId)">
                <template #reference>
                  <DeleteIcon class="absolute bottom-1.5 right-8 hover:-translate-y-0.5 transition" height="23"
                    width="23" />
                </template>
              </el-popconfirm>

              <EditIcon @click="clickUpdate(address)"
                class="absolute bottom-2 right-2 hover:-translate-y-0.5 transition" height="18" width="18" />
            </div>
          </div>

        </div>
      </div>
      <div class="bg-white p-3 shadow-lg rounded-lg w-4/6">
        <h2 class="text-xl font-bold border-b pb-3">我的订单</h2>
        <div v-if="historyOrders.length !== 0" class="overflow-y-auto max-h-[26.5rem] min-h-[26.5rem]"
          v-loading="loading">
          <div class="h-20 relative bg-slate-100 my-2 p-2 rounded-lg bg" v-for="history in historyOrders">
            <p class="absolute text-sm top-2 left-2">收货人：{{ history.oConsignee }}</p>
            <p class="absolute text-sm top-2 left-1/2">联系方式：{{ history.oPhone }}</p>
            <p class="absolute text-xs bottom-2 left-2">总价：￥{{ history.oTotalPrice }}</p>
            <p class="absolute text-xs bottom-2 left-1/4">
              下单时间：{{ formatDateTime(history.oOrderTime) }}
            </p>
            <div class="absolute hover:cursor-pointer hover:bg-opacity-80 text-sm top-2 right-2">
              <el-tag class="absolute top-1 right-20" :type="history.oState === 0 ? 'danger' : 'primary'">
                {{ history.oState === 0
      ? '未支付订单' :
      history.oState === 1 ? '已支付' : '已取消'
                }}
              </el-tag>
              <div class="px-4 py-2 rounded-lg bg-[#fdf5f6] text-red-500 border border-red-500 "
                v-if="history.oState === 1 || history.oState === 2" @click="handelViewOrderDetail(history)">
                详情
              </div>
              <div @click="router.push({ name: 'PayOrder', query: { orderId: history.oId } })"
                class="px-4 py-2 text-white rounded-lg bg-primary" v-else>
                去支付
              </div>
            </div>
          </div>
        </div>

        <div v-else class="overflow-y-auto max-h-[26.5rem] min-h-[26.5rem] bg-white flex flex-col justify-center items-center h-ful">
          <img class="h-44 w-44" src="../assets/image/goodsEmpty.svg" alt="empty">
          <p class="text-slate-400 mt-3">暂无订单</p>
        </div>
        
        <el-dialog v-model="orderDetail.visible" top="5vh">
          <h4 class="m-3 text-xl font-bold">订单基本信息</h4>
          <div class="detail-box grid-cols-4 grid justify-center text-center">
            <p>收货人</p>
            <div> {{ orderDetail.data.oConsignee }} </div>
            <p>联系方式</p>
            <div> {{ orderDetail.data.oPhone }} </div>
            <p>付款价格</p>
            <div> {{ orderDetail.data.oTotalPrice }} </div>
            <p>备注</p>
            <div> {{ orderDetail.data.oRemark }} </div>
            <p>收货地址</p>
            <div> {{ formatAddress(orderDetail.data.oAddressId) }}</div>
            <p>下单时间</p>
            <div> {{ formatDateTime(orderDetail.data.oOrderTime) }} </div>
          </div>
          <h4 class="m-3 text-xl font-bold">订单明细</h4>
          <div class="table-container max-h-[24rem] overflow-y-auto">
            <table>
              <thead>
                <tr class="w-full">
                  <th>商品图片</th>
                  <th>商品名称</th>
                  <th>规格</th>
                  <th>价格</th>
                  <th>数量</th>
                  <th>小计</th>
                </tr>
              </thead>
              <tbody class="max-h-[20rem] overflow-y-auto">
                <tr v-for="item in orderDetail.data.orderGoodsList">
                  <td>
                    <img class="w-24 h-24" :src="item.goods.goodsPhoto" alt="photo" />
                  </td>
                  <td>{{ item.goods.goodsName }}</td>
                  <td>
                    <div v-for="(value, key) in JSON.parse(item.goodsSpecs.goodsSpecs)">
                      <el-tag type="primary" size="small">{{ value }}</el-tag>
                    </div>
                  </td>
                  <td> {{ item.goodsSpecs.goodsPrice }}</td>
                  <td> {{ item.cgNum }} </td>
                  <td> {{ item.cgPrice }} </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-dialog>
      </div>
    </div>
  </DefaultLayout>

</template>
<style scope>
.detail-box p {
  width: 100%;
  padding: .5rem;
  border-bottom: 1px solid #d3d3d3;
  background-color: #e5e4e4;
}

.detail-box div {
  width: 100%;
  padding: .5rem;
  background-color: #f2f2f2;
}

.table-container table {
  width: 100%;
  border-collapse: collapse;
}

.table-container thead {
  position: sticky;
  top: -0.5px;
  /* 使表头固定在表格顶部 */
  z-index: 1;
}

.table-container th {
  border: 1px solid #e8e8e8;
  padding: 8px;
  text-align: center;
}

.table-container td {
  border: 1px solid #e8e8e8;
  padding: 8px;
  text-align: center;
}

.table-container th {
  background-color: #f2f2f2;
}

.main {
  width: 100%;
}

/* .mySelect .el-select-dropdown__item{
    color: black !important;
} */
.el-select-dropdown__item.is-selected {
  color: #d0021b;
}
</style>
